package com.lsx.logistics;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.UUID;

/**
 * @Author: Liang
 * @Date: 2021/12/27
 * @Description:
 */
@Slf4j
public class JwtUtil {
    public static String getToken(String empId, String role, long expiration, String signature){

        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                //设置header
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //设置payload
                .claim("empId", empId)
                .claim("role", role)
                //设置主题 自定义
                .setSubject("account-info")
                //设置过期时间
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                //设置token id
                .setId(UUID.randomUUID().toString())
                //设置签名
                .signWith(SignatureAlgorithm.HS256, signature)
                //将三部分连接
                .compact();
        log.info("生成的token为：{}", jwtToken);
        return jwtToken;
    }
    
    public static String getInfo(String jwtToken, String signature){
        /************* token 解析 ************/
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey(signature).parseClaimsJws(jwtToken);
        //获取claims部分
        Claims claims = claimsJws.getBody();
        //根据key 获取 value
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("empId", claims.get("empId"));
        jsonObject.put("role", claims.get("role"));
        jsonObject.put("id", claims.getId());
        jsonObject.put("subject", claims.getSubject());
        jsonObject.put("expiration", claims.getExpiration());
        return jsonObject.toJSONString();
    }

    public static void main(String[] args) {
        System.out.println(getToken("test", "admin", 450000, "test"));
    }

}
